import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:qilo/core/constants/app_colors.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import '../../../core/providers/global_state_coordinator.dart';
import '../../../core/utils/app_utils.dart';
import '../../../core/routes/navigation_helper.dart';

class AuthPage extends StatefulWidget {
  const AuthPage({super.key});

  @override
  State<AuthPage> createState() => _AuthPageState();
}

class _AuthPageState extends State<AuthPage> {
  bool _isLoginMode = true;

  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _confirmPasswordController =
      TextEditingController();

  @override
  void initState() {
    super.initState();
    _usernameController.text = 'admin';
    _passwordController.text = '123456';
  }

  @override
  void dispose() {
    _usernameController.dispose();
    _passwordController.dispose();
    _confirmPasswordController.dispose();
    super.dispose();
  }

  void _toggleMode() {
    setState(() {
      _isLoginMode = !_isLoginMode;
    });
  }

  Future<void> _handleSubmit() async {
    if (_usernameController.text.trim().isEmpty) {
      AppUtils.showError(
        context,
        _isLoginMode ? 'Please enter username' : 'Please enter account name',
      );
      return;
    }

    if (_passwordController.text.isEmpty) {
      AppUtils.showError(context, 'Please enter password');
      return;
    }

    if (_passwordController.text.length < 6) {
      AppUtils.showError(context, 'Password must be at least 6 characters');
      return;
    }

    if (!_isLoginMode) {
      if (_confirmPasswordController.text.isEmpty) {
        AppUtils.showError(context, 'Please confirm your password');
        return;
      }

      if (_confirmPasswordController.text != _passwordController.text) {
        AppUtils.showError(context, 'Passwords do not match');
        return;
      }
    }

    AppUtils.showLoading(
      context,
      message: _isLoginMode ? 'Logging in...' : 'Registering...',
    );

    try {
      if (_isLoginMode) {
        final coordinator = context.read<GlobalStateCoordinator>();
        final success = await coordinator.login(
          _usernameController.text.trim(),
          _passwordController.text,
        );

        if (mounted) {
          await Future.delayed(const Duration(seconds: 2));

          if (mounted) {
            AppUtils.hideLoading(context);

            if (success) {
              AppUtils.showSuccess(context, 'Login successful!');
              NavigationHelper.pop();
            } else {
              AppUtils.showError(context, 'Invalid username or password');
            }
          }
        }
      } else {
        final coordinator = context.read<GlobalStateCoordinator>();
        final success = await coordinator.register(
          _usernameController.text.trim(),
          _passwordController.text,
          userName: _usernameController.text.trim(),
        );

        if (mounted) {
          await Future.delayed(const Duration(seconds: 2));

          if (mounted) {
            AppUtils.hideLoading(context);

            if (success) {
              AppUtils.showSuccess(
                context,
                'Registration successful! Please login with your new account',
              );
              setState(() {
                _isLoginMode = true;
              });
              _confirmPasswordController.clear();
            } else {
              AppUtils.showError(
                context,
                'Registration failed, account already exists',
              );
            }
          }
        }
      }
    } catch (e) {
      if (mounted) {
        AppUtils.hideLoading(context);
        AppUtils.showError(context, 'Operation failed, please try again');
      }
    }
  }

  void _handleAppleSignIn() async {
    final credential = await SignInWithApple.getAppleIDCredential(
      scopes: [
        AppleIDAuthorizationScopes.email,
        AppleIDAuthorizationScopes.fullName,
      ],
    );
    final coordinator = context.read<GlobalStateCoordinator>();
    final success = await coordinator.login('admin', '123456');

    if (mounted) {
      await Future.delayed(const Duration(seconds: 2));

      if (mounted) {
        AppUtils.hideLoading(context);

        if (success) {
          AppUtils.showSuccess(context, 'Login successful!');
          NavigationHelper.pop();
        } else {
          AppUtils.showError(context, 'Login failed');
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/auth-bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              Align(
                alignment: Alignment.topLeft,
                child: Padding(
                  padding: EdgeInsets.all(16.w),
                  child: Container(
                    width: 30.w,
                    height: 30.w,
                    decoration: BoxDecoration(
                      color: Colors.white.withValues(alpha: 0.9),
                      shape: BoxShape.circle,
                    ),
                    child: IconButton(
                      onPressed: () => Navigator.of(context).pop(),
                      padding: EdgeInsets.zero,
                      iconSize: 16.w,
                      icon: const Icon(
                        Icons.arrow_back_ios_new,
                        color: Colors.black,
                      ),
                    ),
                  ),
                ),
              ),

              const Spacer(),

              _buildMainContent(),

              SizedBox(height: 20.h),

              _buildSubmitButton(),

              SizedBox(height: 20.h),

              _buildBottomSection(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildMainContent() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 10.w),
      decoration: BoxDecoration(
        color: Colors.grey.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(40.r),
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(40.r),
        child: BackdropFilter(
          filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
          child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(40.r),
              image: DecorationImage(
                image: AssetImage(
                  _isLoginMode
                      ? 'assets/images/login-bg.png'
                      : 'assets/images/sign-bg.png',
                ),
                fit: BoxFit.fill,
              ),
            ),
            child: Column(
              children: [_buildTabSwitcher(), _buildFormContainer()],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildTabSwitcher() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.transparent,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(30.r),
          topRight: Radius.circular(30.r),
        ),
      ),
      child: Row(
        children: [
          Expanded(
            child: GestureDetector(
              onTap: _isLoginMode ? null : _toggleMode,
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 16.h),
                decoration: BoxDecoration(color: Colors.transparent),
                child: Text(
                  'Log In',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 20.sp,
                    fontFamily: 'Poppins',
                    fontWeight: FontWeight.w700,
                    color:
                        !_isLoginMode ? AppColors.white : AppColors.tabSelect,
                  ),
                ),
              ),
            ),
          ),
          Expanded(
            child: GestureDetector(
              onTap: _isLoginMode ? _toggleMode : null,
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 16.h),
                decoration: BoxDecoration(
                  color: !_isLoginMode ? Colors.white : Colors.transparent,
                  borderRadius: BorderRadius.only(
                    topRight: Radius.circular(25.r),
                  ),
                ),
                child: Text(
                  'Sign Up',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 20.sp,
                    fontFamily: 'Poppins',
                    fontWeight: FontWeight.w700,
                    color:
                        !_isLoginMode ? AppColors.tabSelect : AppColors.white,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFormContainer() {
    return Container(
      padding: EdgeInsets.all(30.w),
      decoration: BoxDecoration(
        color: Colors.transparent,
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(25.r),
          bottomRight: Radius.circular(25.r),
        ),
      ),
      child: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            SizedBox(height: 20.h),

            _buildInputField(
              label: _isLoginMode ? 'Username' : 'Enter your account name',
              hint:
                  _isLoginMode
                      ? 'Enter your username'
                      : 'Enter your account name',
              controller: _usernameController,
            ),

            SizedBox(height: 24.h),

            _buildInputField(
              label: 'Password',
              hint: 'Enter your password',
              isPassword: true,
              controller: _passwordController,
            ),

            if (!_isLoginMode) ...[
              SizedBox(height: 24.h),
              _buildInputField(
                label: 'Re-confirm your password',
                hint: 'Re-confirm your password',
                isPassword: true,
                controller: _confirmPasswordController,
              ),
            ],

            SizedBox(height: 20.h),
          ],
        ),
      ),
    );
  }

  Widget _buildInputField({
    required String label,
    required String hint,
    bool isPassword = false,
    TextEditingController? controller,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (_isLoginMode) ...[
          Text(
            label,
            style: TextStyle(
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              color: Colors.black87,
            ),
          ),
          SizedBox(height: 8.h),
        ],
        Container(
          height: 50.h,
          decoration: BoxDecoration(
            color: Colors.grey[50],
            borderRadius: BorderRadius.circular(12.r),
            border: Border.all(color: Colors.grey[300]!, width: 1),
          ),
          child: TextFormField(
            controller: controller,
            obscureText: isPassword,
            textAlignVertical: TextAlignVertical.center,
            style: TextStyle(fontSize: 16.sp, color: Colors.black87),
            decoration: InputDecoration(
              hintText: hint,
              hintStyle: TextStyle(fontSize: 16.sp, color: Colors.grey[400]),
              border: InputBorder.none,
              contentPadding: EdgeInsets.symmetric(
                horizontal: 16.w,
                vertical: 15.h,
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildSubmitButton() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 30.w),
      width: double.infinity,
      height: 56.h,
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          colors: [Color(0xFFD2691E), Color(0xFFCD853F)],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: [
          BoxShadow(
            color: const Color(0xFFD2691E).withValues(alpha: 0.4),
            blurRadius: 8,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: _handleSubmit,
          borderRadius: BorderRadius.circular(12.r),
          child: Center(
            child: Text(
              _isLoginMode ? 'Log In' : 'Sign Up',
              style: TextStyle(
                fontSize: 24.sp,
                fontFamily: 'Poppins',
                fontWeight: FontWeight.w700,
                color: Colors.white,
                shadows: const [
                  Shadow(
                    color: Colors.black26,
                    blurRadius: 2,
                    offset: Offset(0, 1),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildBottomSection() {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            Colors.transparent,
            Colors.black.withValues(alpha: 0.2),
            Colors.black.withValues(alpha: 0.4),
            Colors.black.withValues(alpha: 0.6),
          ],
        ),
      ),
      child: Column(
        children: [
          Container(
            margin: EdgeInsets.symmetric(horizontal: 30.w),
            width: double.infinity,
            height: 56.h,
            decoration: BoxDecoration(
              color: Colors.black,
              borderRadius: BorderRadius.circular(12.r),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withValues(alpha: 0.3),
                  blurRadius: 8,
                  offset: const Offset(0, 4),
                ),
              ],
            ),
            child: Material(
              color: Colors.transparent,
              child: InkWell(
                onTap: _handleAppleSignIn,
                borderRadius: BorderRadius.circular(12.r),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.apple, color: Colors.white, size: 24.w),
                    SizedBox(width: 2.w),
                    Text(
                      'Continue with Apple',
                      style: TextStyle(
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w600,
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),

          SizedBox(height: 20.h),

          Padding(
            padding: EdgeInsets.symmetric(horizontal: 20.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Flexible(
                  child: Text(
                    'By continuing, you agree to our ',
                    style: TextStyle(fontSize: 10.sp, color: Colors.white),
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    AppUtils.openUrl(
                      'https://www.freeprivacypolicy.com/live/d17327ba-4512-48f5-b743-6215587159ec',
                    );
                  },
                  child: Text(
                    'Terms of Service',
                    style: TextStyle(
                      fontSize: 10.sp,
                      decoration: TextDecoration.underline,
                      fontWeight: FontWeight.w500,
                      color: Colors.white,
                      decorationColor: Colors.white,
                    ),
                  ),
                ),
                Text(
                  ' and ',
                  style: TextStyle(fontSize: 10.sp, color: Colors.white),
                ),
                GestureDetector(
                  onTap: () {
                    AppUtils.openUrl(
                      'https://www.freeprivacypolicy.com/live/82e54f5c-a3a3-4bc8-a08a-0da176425cf4',
                    );
                  },
                  child: Text(
                    'EULA',
                    style: TextStyle(
                      fontSize: 10.sp,
                      decoration: TextDecoration.underline,
                      fontWeight: FontWeight.w500,
                      color: Colors.white,
                      decorationColor: Colors.white,
                    ),
                  ),
                ),
              ],
            ),
          ),

          SizedBox(height: 36.h),
        ],
      ),
    );
  }
}
